package com.lagou.edu.filter;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by shixi  on 2021/1/29
 */
@Slf4j
@Component
@Order(0)
public class IpFilter implements GlobalFilter {

    //存储每个ip请求的访问量 key=ip; value=访问时间
    private volatile static Map<String, LinkedList<Long>> ipMap = new ConcurrentHashMap<>();

    //最大请求数
    @Value("${ip.maxreqnum}")
    private Integer ipMaxReqNum;
    //多少分钟内
    @Value("${ip.minute}")
    private Integer ipMinute;
    /*
    爆刷分析：
    1、记录每个ip请求的时间
    2、统计从当前时间开始，前推 imMinute 分钟，统计出共请求多少次
    3、如果达到 ipMaxReqNum 限制，则。。。
    4、每次同ip请求时，将过期的时间请求记录清楚，以释放空间
     */

    private final String errMsg = "您频繁进行操作，请求已被拒绝!";

    private static final String REQUEST_TIME_BEGIN = "requestTimeBegin";

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("    IpFilter ... ");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String ip = request.getRemoteAddress().getAddress().getHostAddress();
        ip = ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
        LinkedList<Long> times = ipMap.get(ip);
        if (times == null) {
            times = new LinkedList<>();
            times.add(System.currentTimeMillis());
            ipMap.put(ip, times);
        } else {
            times.add(System.currentTimeMillis());
//            ipMap.put(ip, times);//调用次数加一
        }

        int reqNum = getReqNum(ipMap.get(ip));//根据请求 ipMinute 限制，获取请求总数

        log.info(ip + " , " + ipMinute + "分钟内，请求次数共" + reqNum + ", 阈值="+ ipMaxReqNum);
        if (reqNum > ipMaxReqNum) {//超过请求阈值
            log.info("超过请求阈值：" + ipMaxReqNum);
            response.setStatusCode(HttpStatus.SEE_OTHER);
            DataBuffer wrap = response.bufferFactory().wrap(errMsg.getBytes("utf-8"));
            return response.writeWith(Mono.justOrEmpty(wrap));
        }

        //合法请求放行
        exchange.getAttributes().put(REQUEST_TIME_BEGIN, System.currentTimeMillis());
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    Long startTime = exchange.getAttribute(REQUEST_TIME_BEGIN);
                    if (startTime != null) {
                        log.info("    " + exchange.getRequest().getURI().getRawPath() + ": " + (System.currentTimeMillis() - startTime) + "ms");
                    }
                })
        );
    }

    private int getReqNum(LinkedList<Long> times) {
        int l = ipMinute * 60 * 1000;
        int reqNum =0;
        for (Long time : times) {
            if (System.currentTimeMillis() - l > time ) {//数据过期，删除
                //log.info("请求时间过期,删除: "+time);
            }else{//未过期 +1
                reqNum++;
            }
        }
        return reqNum;
    }

}
